package com.jindy.module.outgoingapproval.service.impl;

import com.jindy.activiti.service.IProcessService;
import com.jindy.common.constant.Constants;
import com.jindy.common.exception.base.BaseException;
import com.jindy.common.utils.DateUtils;
import com.jindy.common.utils.SecurityUtils;
import com.jindy.common.utils.StringUtils;
import com.jindy.jpush.utils.UniJpushUtils;
import com.jindy.module.approvalRecord.domain.ApprovalRecord;
import com.jindy.module.approvalRecord.mapper.ApprovalRecordMapper;
import com.jindy.module.jpush.mapper.JpushMapper;
import com.jindy.module.oacopy.service.ISyOaCopyService;
import com.jindy.module.oacopyconfig.domain.SyOaCopyConfig;
import com.jindy.module.oacopyconfig.mapper.SyOaCopyConfigMapper;
import com.jindy.module.outgoingapproval.domain.OutgoingApprovalVO;
import com.jindy.module.outgoingapproval.domain.SyOutgoingApproval;
import com.jindy.module.outgoingapproval.mapper.SyOutgoingApprovalMapper;
import com.jindy.module.outgoingapproval.service.ISyOutgoingApprovalService;
import com.jindy.module.serialNum.service.ISySerialNumTService;
import com.jindy.module.syTableRecord.service.ISyTableRecordTService;
import com.jindy.system.domain.SysUserRoleDeptInfo;
import com.jindy.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 外出审批Service业务层处理
 *
 * @author jindy
 * @date 2023-05-12
 */
@Service
public class SyOutgoingApprovalServiceImpl implements ISyOutgoingApprovalService {

    private static final Logger LOGGER = LoggerFactory.getLogger(SyOutgoingApprovalServiceImpl.class);
    @Resource
    private SyOutgoingApprovalMapper syOutgoingApprovalMapper;

    @Autowired
    private IProcessService processService;

    /**
     * 抄送Service
     */
    @Resource
    private ISyOaCopyService syOaCopyService;

    /**
     * 用户Service
     */
    @Resource
    private ISysUserService sysUserService;

    /**
     * 配置表
     */
    @Resource
    private SyOaCopyConfigMapper syOaCopyConfigMapper;

    /**
     * 生成流水单号Service
     */
    @Resource
    private ISySerialNumTService serialNumTService;

    /**
     * 生成流水单号Service
     */
    @Resource
    private ApprovalRecordMapper approvalRecordMapper;

    /**
     * 设备Mapper
     */
    @Resource
    private JpushMapper jpushMapper;

    /**
     * 存储表Service
     */
    @Resource
    private ISyTableRecordTService iSyTableRecordTService;



    /**
     * 查询外出审批
     *
     * @param id 外出审批主键
     * @return 外出审批
     */
    @Override
    public SyOutgoingApproval selectSyOutgoingApprovalById(Long id) {
        return syOutgoingApprovalMapper.selectSyOutgoingApprovalById(id);
    }

    /**
     * 查询外出审批列表
     *
     * @param syOutgoingApproval 外出审批
     * @return 外出审批
     */
    @Override
    public List<SyOutgoingApproval> selectSyOutgoingApprovalList(SyOutgoingApproval syOutgoingApproval) {
        if (!SecurityUtils.isAdmin(SecurityUtils.getLoginUser().getUser().getUserId())) {
            syOutgoingApproval.setCreateBy(SecurityUtils.getUsername());
        }
        List<SyOutgoingApproval> list = syOutgoingApprovalMapper.selectSyOutgoingApprovalList(syOutgoingApproval);
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(item -> {
                try {
                    processService.richProcessField(item);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
        return list;
    }


    /**
     * 查询外出审批列表（含业务状态）
     *
     * @param syOutgoingApproval 外出审批
     * @return 外出审批
     */
    @Override
    public List<OutgoingApprovalVO> selectSyOutGoingApprovalResult(SyOutgoingApproval syOutgoingApproval) {
        List<OutgoingApprovalVO> list = syOutgoingApprovalMapper.selectSyOutGoingApprovalResult(syOutgoingApproval);
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(item -> {
                try {
                    processService.richProcessField(item);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
        return list;

    }

    /**
     * 新增外出审批
     *
     * @param syOutgoingApproval 外出审批
     * @return 结果
     */
    @Override
    public int insertSyOutgoingApproval(SyOutgoingApproval syOutgoingApproval) {
        // 生成流水单号
        String serialNum = serialNumTService.generateSerialNum("WCSP");
        if (StringUtils.isBlank(serialNum)) {
            throw new BaseException("新增外出审批-获取外出单号失败");
        }
        syOutgoingApproval.setSerialNum(serialNum);
        syOutgoingApproval.setCreateTime(DateUtils.getNowDate());
        syOutgoingApproval.setBusinessStatus(Constants.DRAFT);
        iSyTableRecordTService.saveEntityAndTable(syOutgoingApproval,serialNum);
        return syOutgoingApprovalMapper.insertSyOutgoingApproval(syOutgoingApproval);
    }

    /**
     * 修改外出审批
     *
     * @param syOutgoingApproval 外出审批
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateSyOutgoingApproval(SyOutgoingApproval syOutgoingApproval) {
        syOutgoingApproval.setUpdateTime(DateUtils.getNowDate());
        return syOutgoingApprovalMapper.updateSyOutgoingApproval(syOutgoingApproval);
    }

    /**
     * 批量删除外出审批
     *
     * @param ids 需要删除的外出审批主键
     * @return 结果
     */
    @Override
    public int deleteSyOutgoingApprovalByIds(Long[] ids) {
        return syOutgoingApprovalMapper.deleteSyOutgoingApprovalByIds(ids);
    }

    /**
     * 删除外出审批信息
     *
     * @param id 外出审批主键
     * @return 结果
     */
    @Override
    public int deleteSyOutgoingApprovalById(Long id) {
        return syOutgoingApprovalMapper.deleteSyOutgoingApprovalById(id);
    }

    /**
     * 提交申请
     *
     * @param outgoingApproval
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void submitApply(SyOutgoingApproval outgoingApproval) throws Exception {
        // 初始化值
        Map<String, Object> variables = createVariables(outgoingApproval);
        // 启动流程
        processService.submitApply(outgoingApproval, "outgoing", variables);
        // 添加抄送人
        syOaCopyService.addCopyUsers("WCSP", outgoingApproval.getId());
        //新增审批记录
        List<Long> longs = addApprovalRecord(outgoingApproval, variables);
        // 通知审批人
        sendApproveMessage(longs);
        outgoingApproval.setBusinessStatus(Constants.APPROVE);
        updateSyOutgoingApproval(outgoingApproval);
    }


    /**
     * 逻辑流初始化
     *
     * @param outgoingApproval
     * @return
     */
    public Map<String, Object> createVariables(SyOutgoingApproval outgoingApproval) {
        Map<String, Object> var = new HashMap<>(500);
        // 判断申请人是否是主管
        List<SysUserRoleDeptInfo> userList = sysUserService.selectUsersByUserName(outgoingApproval.getApplyUserName());
        if (CollectionUtils.isEmpty(userList)) {
            throw new BaseException("外出审批-判断是否为直接主管集合为空");
        }
        List<SysUserRoleDeptInfo> collect = userList.stream().filter(a -> "直接主管".equals(a.getRoleName())).collect(Collectors.toList());
        if (collect.size() > 0) {
             //   申请人是直接主管,由余总审批
            SyOaCopyConfig syOaCopyConfig = new SyOaCopyConfig();
            syOaCopyConfig.setNumber("WCSP_LEADER");
            List<SyOaCopyConfig> syOaCopyConfigs = syOaCopyConfigMapper.selectSyOaCopyConfigList(syOaCopyConfig);
            if (CollectionUtils.isEmpty(syOaCopyConfigs)) {
                throw new BaseException("createVariables", "获取领导负责人失败");
            }
            var.put("leader", syOaCopyConfigs.get(0).getCopyUserName());
            var.put("leaderId",syOaCopyConfigs.get(0).getCopyUserId());
        } else {
            //   申请人不是直接主管,由直接主管审批
            var.put("leader", userList.get(0).getLeader());
            var.put("leaderId",userList.get(0).getLeaderId());
        }
        return var;
    }

    /**
     * 发起人是内部人员 流程记录
     *
     * @param outgoingApproval
     * @param map
     */
    @Transactional(rollbackFor = Exception.class)
    public List<Long> addApprovalRecord(SyOutgoingApproval outgoingApproval, Map<String, Object> map) {

        int sequence = 1;
        //  发起人
        ApprovalRecord firstApprovalRecord = getApprovalRecord(outgoingApproval);
        firstApprovalRecord.setSequence(sequence);
        firstApprovalRecord.setApprovalStatus(Constants.COMPLETED);
        firstApprovalRecord.setTypeOperation(Constants.AGREE);
        firstApprovalRecord.setBusinessStatus(Constants.APPROVE);
        firstApprovalRecord.setApproverId(Long.valueOf(outgoingApproval.getApplyUserId()));
        firstApprovalRecord.setApproverName(outgoingApproval.getApplyUserName());
        approvalRecordMapper.insertApprovalRecord(firstApprovalRecord);

        sequence++;
        //  第二审批人
        ApprovalRecord secondApprovalRecord = getApprovalRecord(outgoingApproval);
        secondApprovalRecord.setSequence(sequence);
        secondApprovalRecord.setApprovalStatus(Constants.APPROVE);
        secondApprovalRecord.setApproverId((Long) map.get("leaderId"));
        secondApprovalRecord.setApproverName((String) map.get("leader"));
        approvalRecordMapper.insertApprovalRecord(secondApprovalRecord);

        return Collections.singletonList((Long) map.get("leaderId"));
    }

    /**
     * 获取审批记录对象
     *
     * @param outgoingApproval
     * @return
     */
    private ApprovalRecord getApprovalRecord(SyOutgoingApproval outgoingApproval) {
        ApprovalRecord approvalRecord = new ApprovalRecord();
        approvalRecord.setSerialNum(outgoingApproval.getSerialNum());
        approvalRecord.setUserId(Long.valueOf(outgoingApproval.getApplyUserId()));
        approvalRecord.setOrderId(outgoingApproval.getId());
        approvalRecord.setUserName(outgoingApproval.getApplyUserName());
        approvalRecord.setUpdateTime(DateUtils.parseDate(DateUtils.getTime()));
        approvalRecord.setUpdateBy(outgoingApproval.getApplyUserName());
        approvalRecord.setCreateBy(outgoingApproval.getApplyUserName());
        approvalRecord.setCreateTime(DateUtils.parseDate(DateUtils.getTime()));
        return approvalRecord;
    }

    /**
     * 给审批人推送消息
     * @param addJpushList
     */
    private void sendApproveMessage(List<Long> addJpushList) {
        try {
            List<String> addRegIds = jpushMapper.selectRegistrationIdsByUserIds(addJpushList);
            if (!CollectionUtils.isEmpty(addRegIds)){
                UniJpushUtils.sendApproveMessage(addRegIds);
            }
        } catch (Exception e) {
            LOGGER.error("外出审批审批人推送通知失败",e);
        }
    }

}
